package com.megalith.service.impl;

import com.megalith.constant.ResultCode;
import com.megalith.dto.ManagerVerifyDTO;
import com.megalith.dto.StaffApplyDTO;
import com.megalith.dto.StaffLeaveTicketDTO;
import com.megalith.service.ListenerTaskService;
import com.megalith.vo.Result;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2022/7/17
 * @Version 1.0
 */
@Service
public class ListenerTaskServiceImpl implements ListenerTaskService {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Override
    public String startListenerProcess(StaffApplyDTO applyDTO) {
        String processDefinitionkey = "listenerLeaveProcess";

        Map<String,Object> param = new HashMap<>();
        param.put("staff",applyDTO.getName());
        param.put("manager",applyDTO.getManager());
        param.put("humanResources",applyDTO.getHumanResources());
        param.put("generalManager",applyDTO.getGeneralManager());

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionkey, param);
        return processInstance.getId();
    }

    @Override
    public Result fillListenerTaskTicket(StaffLeaveTicketDTO leaveTicketDTO) {
        String processDefinitionkey = "listenerLeaveProcess";

        Task task = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionkey)
                .taskAssignee(leaveTicketDTO.getName())
                .active()
                .singleResult();

        if(task == null){
            return Result.sysError("未查到待办任务");
        }

        Map<String,Object> param = new HashMap<>();
        param.put("days",leaveTicketDTO.getDays());//请假天数
        param.put("reason",leaveTicketDTO.getReason());//请假原因

        taskService.complete(task.getId(),param);

        return Result.ok(ResultCode.TASK_SUCCESS.getDes());
    }

    @Override
    public Result completeManagerTask(ManagerVerifyDTO verifyDTO) {
        String processDefinitionkey = "listenerLeaveProcess";

        Task task = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionkey)
                .taskAssignee(verifyDTO.getManagerName())
                .active()
                .singleResult();

        if(task == null){
            return Result.sysError("未查到待办任务");
        }

        Map<String,Object> param = new HashMap<>();
        param.put("opinion",verifyDTO.getOpinion());//审批意见

        taskService.complete(task.getId(),param);

        return Result.ok(ResultCode.TASK_SUCCESS.getDes());
    }
}
